const express = require("express");
const router = express.Router();
const fs = require("fs");
const process = require("process");
const path = require("path");

router.post("/run", (req, res) => {
  req.app.locals.ws.send("show initial");
  req.app.locals.taskInfo = {
    scene: req.body.scene,
    traj: req.body.traj,
    angle: req.body.angle,
  };
  return res.json({ code: 0 });
});

router.post("/upload", (req, res) => {
  const inputDir = path.join(process.cwd(), "app", "input_images");
  if (!fs.existsSync(inputDir)) {
    fs.mkdirSync(inputDir);
  }
  fs.writeFileSync(
    path.join(inputDir, req.files.image.name),
    req.files.image.data
  );
  res.json({ code: 0 });
});

router.get("/init", (req, res) => {
  const appDir = path.join(process.cwd(), "app");
  if (!fs.existsSync(appDir)) {
    fs.mkdirSync(appDir);
  }
  const inputDir = path.join(process.cwd(), "app", "input_images");
  const outputDir = path.join(process.cwd(), "app", "output_images");
  if (!fs.existsSync(inputDir)) {
    fs.mkdirSync(inputDir);
  }
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir);
  }
  for (let fileName of fs.readdirSync(inputDir)) {
    fs.unlinkSync(path.join(inputDir, fileName));
  }
  for (let fileName of fs.readdirSync(outputDir)) {
    fs.unlinkSync(path.join(outputDir, fileName));
  }
  return res.json({ code: 0 });
});

module.exports = router;
